/**
 * Filename: BrowseAdapter.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/3/13 16:41
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.BrowseActivity;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.ToastUtils;
import com.github.postsanf.yinian.view.ProgressView;
import com.github.postsanf.yinian.view.TouchImageView;
import com.liulishuo.qiniuimageloader.QiniuImageLoader;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;
import java.util.List;
/**
 * 大图浏览适配器
 */
public class BrowseAdapter extends PagerAdapter{

	private Activity 		mContext;
	private List<String>  	mUrls;
	private ArrayList<View> mViews;
	private ImageLoader 	mImageLoader;
	private Boolean 		isLocal=false;

	public BrowseAdapter(Activity mContext, List<String> mUrls ,Boolean isLocal) {
		this.mContext = mContext;
		this.mUrls = mUrls;
		this.mImageLoader = ImageLoader.getInstance();
		this.isLocal = isLocal;
		initImgs();
	}

	public BrowseAdapter(Activity mContext, List<YNPhoto> photos) {
		this.mContext = mContext;
		List<String> urls = new ArrayList<>();
		for (int i=0;i<photos.size();i++){
			urls.add(photos.get(i).getUrl());
		}
		this.mUrls = urls;
		this.mImageLoader = ImageLoader.getInstance();
		initImgs();
	}

	private void initImgs() {
		mViews = new ArrayList<View>();
		for(int i=0; i<mUrls.size(); i++) {
			// 填充显示图片的页面布局
			View view = View.inflate(mContext, R.layout.yn_item_image_browse, null);
			mViews.add(view);
		}
	}

	@Override
	public int getCount() {
		return mUrls.size();
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	@Override
	public View instantiateItem(ViewGroup container, int position) {
		View view = mViews.get(position);
		final RelativeLayout rl_view_progrese = (RelativeLayout) view.findViewById(R.id.rl_view_progress);
		final TouchImageView iv_image_browser = (TouchImageView) view.findViewById(R.id.iv_image_browse);
		iv_image_browser.setMaxZoom(15);

		String url = mUrls.get(position);
		url = isLocal?"file://" + Uri.parse(url) :  StringUtils.repaceImgUrl(new QiniuImageLoader(mContext, url).formatWebp().createQiniuUrl());

		mImageLoader.displayImage(url, new ImageViewAware(iv_image_browser, false),
				ImageOptHelper.getImgOptions(),new SimpleImageLoadingListener() {
					@Override
					public void onLoadingStarted(String imageUri, View view) {
						rl_view_progrese.setVisibility(View.VISIBLE);
					}

					@Override
					public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
						String message = null;
						switch (failReason.getType()) {     // 获取图片失败类型
							case IO_ERROR:              // 文件I/O错误
								message = "文件错误";
								break;
							case DECODING_ERROR:        // 解码错误
								message = "解码错误";
								break;
							case NETWORK_DENIED:        // 网络延迟
								message = "网络延迟";
								break;
							case OUT_OF_MEMORY:         // 内存不足
								message = "内存不足";
								break;
							case UNKNOWN:               // 原因不明
								message = "未知错误";
								break;
						}
						rl_view_progrese.setVisibility(View.GONE);
//						ToastUtils.showToast(mContext, message, Toast.LENGTH_SHORT);
						SnackBarUtils.makeShort(view,message).show();
					}
					@Override
					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
						float scale = (float) loadedImage.getHeight() / loadedImage.getWidth();
						int screenWidthPixels = DisplayUtils.getScreenWidthPixels(mContext);
						int screenHeightPixels = DisplayUtils.getScreenHeightPixels(mContext);
						int height = (int) (screenWidthPixels * scale);

						if(height < screenHeightPixels) {
							height = screenHeightPixels;
						}
						ViewGroup.LayoutParams params = iv_image_browser.getLayoutParams();
						params.height = height;
						params.width = screenWidthPixels;
						iv_image_browser.setImageBitmap(loadedImage);
						rl_view_progrese.setVisibility(View.GONE);       // 不显示进度条
					}
				}, new ImageLoadingProgressListener() {
					@Override
					public void onProgressUpdate(String imageUri, View view,
												 int current, int total) {
					}
				});

		container.addView(view);
		return view;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		((ViewPager)container).removeView((View) object);
	}

	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	public String getPic(int position) {
		int total =  mUrls.size()>0? mUrls.size():1;
		return mUrls.get(position % total);
	}

	public Bitmap getBitmap(int position) {
		Bitmap bitmap = null;
		View view = mViews.get(position % mViews.size());
		ImageView iv_image_browser = (ImageView) view.findViewById(R.id.iv_image_browse);
		Drawable drawable = iv_image_browser.getDrawable();
		if(drawable != null && drawable instanceof BitmapDrawable) {
			BitmapDrawable bd = (BitmapDrawable) drawable;
			bitmap = bd.getBitmap();
		}
		return bitmap;
	}
}
